package main

import (
	"github.com/ant0ine/go-json-rest/rest"
	"log"

	"net/http"
	"rocks/cfg"
	"rocks/util"
	//"github.com/Shaked/gomobiledetect"
	"rocks/serv"
	"io/ioutil"
)


func main(){

	api := rest.NewApi()
//		api.Use(rest.DefaultDevStack...)
	api.Use(&rest.CorsMiddleware{
		RejectNonCorsRequests: false,
		OriginValidator: func(origin string, request *rest.Request) bool {
			//			return origin == "http://127.0.0.1"
			return true
		},
		AllowedMethods: []string{"GET", "POST", "PUT","DELETE"},
		AllowedHeaders: []string{
			"Accept", "Content-Type", "tokenId", "tokenid", "Origin", "Authorization","authorization","ukey"},
		AccessControlAllowCredentials: true,
		AccessControlMaxAge:           360000,
	})


	routes:=[]*rest.Route{}
	//routes=append(routes,rest.Get("/ua", uaDetect),)
	rs:=&serv.RSService{}
	rsroutes:=RsNewRoutes(rs)
	routes=append(routes,rsroutes...)
	router, err := rest.MakeRouter(routes...)

	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router);
	//http.Handle("/lc/", http.StripPrefix("/lc",  api.MakeHandler()))
	http.Handle("/",  api.MakeHandler())
	util.LogGreen("server will started http://", *cfg.CServer)
	log.Fatal(http.ListenAndServe(*cfg.CServer,nil))
}

func RsNewRoutes(service serv.RSInterface) []*rest.Route {
	rs:=*service.(*serv.RSService)
	return []*rest.Route{

		rest.Get("/test", test),
		rest.Post("/test", test),

		rest.Get("/neh/*urlWithoutSchecma", rs.GetOnlyWithNeh),
		rest.Post("/neh/*urlWithoutSchecma", rs.PostOnlyWithNeh),

		rest.Get("/ttl/:ttl/neh/*urlWithoutSchecma", rs.GetWithTtlAndNeh),
		rest.Post("/ttl/:ttl/neh/*urlWithoutSchecma", rs.PostWithTtlAndNeh),

		rest.Get("/ttl/:ttl/*urlWithoutSchecma", rs.GetOnlyWithTtl),
		rest.Post("/ttl/:ttl/*urlWithoutSchecma", rs.PostOnlyWithTtl),

		rest.Get("/*urlWithoutSchecma", rs.Get),
		rest.Post("/*urlWithoutSchecma", rs.Post),

		//rest.Get("/wxtoken/:appid/:openid", rs.WXTokenHandler),
		//rest.Get("/info/*token",  rs.InfoHandler),
	}
}
func test(w rest.ResponseWriter, r *rest.Request) {
	//w.Header().Set("Cache-Control","max-age="+strconv.Itoa(int(129)))
	//w.Header().Set("expires","Tue, 18 Oct 2016 12:33:00 GMT")
	log.Println("test handler")
	println(r.Header)
	bs,_:=ioutil.ReadAll(r.Body)
	r.Header["body"]=[]string{string(bs)}
	w.WriteJson(r.Header)
	//w.(http.ResponseWriter).Write(bs)
	//println("header:",r.Header,"body:",string(bs))
}
